package org.example.JDBC;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.util.List;

public class AccountDaolmpl implements AccountDao{

    //定义JdbcTemplate属性和setting方法
    private JdbcTemplate jdbcTemplate;
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    //添加用户
    @Override
    public int addAccount(Account account) {
        String sql = "insert into account(username,balance) value(?,?)";
        //用于存放SQL语句中的参数
        Object[] obj = new Object[]{account.getUsername(),account.getBalance()};
        int num = this.jdbcTemplate.update(sql,obj);
        return num;
    }

    //更新用户
    @Override
    public int updateAccount(Account account) {
        String sql = "update account set username = ?,balance = ? where id = ?";
        Object[] obj = new Object[]{account.getUsername(),account.getBalance(),account.getId()};
        int num = this.jdbcTemplate.update(sql,obj);
        return num;
    }

    //删除用户
    @Override
    public int deleteAccount(int id) {
        String sql = "delete from account where id = ?";
        int num = this.jdbcTemplate.update(sql,id);
        return num;
    }

    //查询所有用户数据
    @Override
    public List<Account> selectAll() {
        String sql = "select * from account";
        //创建一个新的BeanPropertyRowMapper对象。
        //BeanPropertyRowMapper是RowMapper接口的实现类，它可以自动将数据表中的数据映射到用户自定义的类中（自定义类的属性需要和数据表中的字段相对应）。
        RowMapper<Account> rowMapper = new BeanPropertyRowMapper<Account>(Account.class);
        return this.jdbcTemplate.query(sql,rowMapper);
    }

}
